package com.pt5.pthouduan.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pt5.pthouduan.entity.PeerInfo;
import com.pt5.pthouduan.entity.Torrent;
import com.pt5.pthouduan.entity.TrackeredTorrentWithStats;
import com.pt5.pthouduan.entity.User;
import com.pt5.pthouduan.exception.TorrentNotFoundException;
import com.pt5.pthouduan.mapper.UserMapper;
import com.pt5.pthouduan.service.TorrentService;
//import com.pt5.pthouduan.service.TorrentStatsService;
//import com.pt5.pthouduan.service.TrackeredTorrentService;
import com.pt5.pthouduan.service.impl.PeerService;
import com.pt5.pthouduan.service.impl.UserServiceImpl;
import com.turn.ttorrent.bcodec.BDecoder;
import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;
import com.turn.ttorrent.tracker.Tracker;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Controller
@RestController
@CrossOrigin // 允许前端跨域访问
@RequestMapping("/torrent")
public class TorrentController {
    @Autowired
    private TorrentService torrentService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private Tracker tracker;
    @Autowired
    private PeerService peerService;
//    @Autowired
//    private TorrentStatsService statsService;
//    @Autowired
//    private TrackeredTorrentService trackeredTorrentService;


    @GetMapping("/{infoHash}/seeders")
    public ResponseEntity<List<PeerInfo>> getSeedersByInfoHash(@PathVariable String infoHash) {
        List<PeerInfo> seeders = peerService.getSeedersByInfoHash(infoHash.toUpperCase());
        System.out.println("Response: " + seeders);
        return ResponseEntity.ok(seeders);
    }

   //显示所有种子
    @GetMapping("/list")
    public List<Torrent> getAllTorrents() {
        return torrentService.getAllTorrents();
    }
    // 按分类获取种子（带 category 参数）
    @GetMapping("/listByCategory")
    public List<Torrent> getTorrentsByCategory(@RequestParam(required = false) Integer categoryid) {
        if (categoryid == null) {
            return torrentService.getAllTorrents();
        }
        return torrentService.getTorrentsByCategory(categoryid); // 否则按分类过滤
    }
    @GetMapping("/listByCategorywithfilter")
    public List<Torrent> getTorrentsByCategorywithFilter(
            @RequestParam Integer categoryid,
            @RequestParam Map<String, String> filters
    ){
        filters.remove("categoryid");
        List<Torrent> torrents = torrentService.getTorrentsByCategorywithfilters(categoryid,filters);
        return torrents;
    }
    // 获取单个种子详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getTorrentById(@PathVariable Long id) {
        try {
            Torrent torrent = torrentService.getTorrentById(id);
            if (torrent == null) {
                return ResponseEntity.notFound().build(); // 如果种子不存在，返回 404
            }
            System.out.println(torrent);
            return ResponseEntity.ok(torrent); // 返回种子详情
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取种子详情失败: " + e.getMessage());
        }
    }
//未更新前端前
//    @PostMapping("/upload")
//    public ResponseEntity<?> uploadTorrent(
//            @RequestParam("file") MultipartFile torrentFile,
//            @RequestParam("title") String title,
//            @RequestParam("description") String description
//            //@AuthenticationPrincipal User user
//            //User user
//    ){
//        // 创建临时用户对象
//        User user = new User(1L,"testuser");
//        //user.setUserid(1L); // 设置测试用户ID
//        try{
//            //torrentService.Upload(torrentFile,title,description,user);
//            return torrentService.Upload(torrentFile, title, description, user);
//        }catch(Exception e){
//            return ResponseEntity.badRequest().body("Upload failed:" + e.getMessage());
//        }
//    }
//@PostMapping("/upload")
//public ResponseEntity<?> uploadTorrent(
//        @RequestParam("file") MultipartFile torrentFile,
//        @RequestParam("title") String title,
//        @RequestParam("description") String description,
//        @RequestParam("categoryId") Integer categoryId,
//        @RequestParam(value = "dpi",required = false) String dpi,
//        @RequestParam(value = "caption", required = false) String caption){
//    // 创建临时用户对象
//    User user = new User(1L,"testuser");
//    //user.setUserid(1L); // 设置测试用户ID
//    try{
//        //torrentService.Upload(torrentFile,title,description,user);
//        return torrentService.Upload(torrentFile, title, description, categoryId, dpi,caption,user);
//    }catch(Exception e){
//        return ResponseEntity.badRequest().body("Upload failed:" + e.getMessage());
//    }
//}
@PostMapping("/upload")
public ResponseEntity<?> uploadTorrent(
        @RequestParam("file") MultipartFile torrentFile,
        @RequestParam("title") String title,
        @RequestParam("description") String description,
        @RequestParam("categoryId") Integer categoryId,
        // 以下为通用扩展字段（根据类型选择性使用）
        @RequestParam(value = "dpi",required = false) String dpi,
        @RequestParam(value = "caption", required = false) String caption,
        @RequestParam(value = "region", required = false) String region,
        @RequestParam(value = "year", required = false) Integer year,
        @RequestParam(value = "genre", required = false) String genre,
        @RequestParam(value = "format", required = false) String format,
        @RequestParam(value = "resolution", required = false) String resolution,
        @RequestParam(value = "codecFormat", required = false) String codecFormat,
        @RequestParam(value = "platform", required = false) String platform,
        @RequestParam(value = "language", required = false) String language,
        @RequestParam(value = "eventType", required = false) String eventType,
        @RequestParam(value = "dataType", required = false) String dataType,
        @RequestParam(value = "source", required = false) String source,
        @RequestParam(value = "style", required = false) String style,
        @RequestParam(value = "isMainland", required = false) Boolean isMainland){
    // 创建临时用户对象
    User user = new User(1L,"testuser");
    // 构建扩展参数Map
    Map<String, String> extraParams = new HashMap<>();

    // 通用参数
    putIfNotNull(extraParams, "dpi", dpi);
    putIfNotNull(extraParams, "caption", caption);
    putIfNotNull(extraParams, "region", region);
    putIfNotNull(extraParams, "year", year != null ? year.toString() : null);
    putIfNotNull(extraParams, "genre", genre);
    putIfNotNull(extraParams, "format", format);
    putIfNotNull(extraParams, "resolution", resolution);

    // 特殊参数
    putIfNotNull(extraParams, "codecFormat", codecFormat);  // 电影编码格式
    putIfNotNull(extraParams, "platform", platform);        // 游戏/软件平台
    putIfNotNull(extraParams, "language", language);        // 游戏语言
    putIfNotNull(extraParams, "eventType", eventType);      // 体育赛事类型
    putIfNotNull(extraParams, "source", source);            // 纪录片来源
    putIfNotNull(extraParams, "style", style);              // 音乐风格
    putIfNotNull(extraParams, "isMainland", isMainland != null ? isMainland.toString() : null); // 综艺是否大陆
    putIfNotNull(extraParams, "dataType", dataType);
//    extraParams.put("region", "CN");
//    extraParams.put("year", "2023");
//    extraParams.put("genre", "Action");
//    extraParams.put("encodeFormat", "H.264");
//    extraParams.put("resolution", "1080p");


    //user.setUserid(1L); // 设置测试用户ID
    try{
        //torrentService.Upload(torrentFile,title,description,user);
        //return torrentService.Upload(torrentFile, title, description, categoryId, dpi,caption,user);

//        return torrentService.uploadWithCategory(
//                torrentFile, title, description, categoryId, user, dpi, caption,
//                region, year, genre, format, resolution, codecFormat,
//                platform, language, eventType, source, style, isMainland
//        );
        // 调用Service
        return torrentService.uploadWithCategory(
                torrentFile,
                title,
                description,
                categoryId,
                user,
                extraParams
        );
    }catch(Exception e){
        return ResponseEntity.badRequest().body("Upload failed:" + e.getMessage());
    }
}
    // 辅助方法：避免重复的空值判断
    private void putIfNotNull(Map<String, String> map, String key, String value) {
        if (value != null) {
            map.put(key, value);
        }
    }

//    @GetMapping("/download/{id}")
//    public ResponseEntity<Resource> downloadTorrent(@PathVariable Long id, HttpServletRequest request){
//        try{
//            //获取种子文件资源
//            Torrent torrentFile = torrentService.getTorrentFile(id);            //确定文件内容类型
//            String filePath = torrentFile.getFilePath();
//            File file = new File(filePath);
//            if(!file.exists()){
//                return ResponseEntity.notFound().build();  //如果文件不存在就返回异常
//            }
//            String contentType = request.getServletContext().getMimeType(torrentFile.getFilePath());
//            if(contentType == null){
//                contentType = "application/octet-stream";  //如果没有文件类型，默认使用二进制流
//            }
//            //构建resource对象
//            Resource resource = torrentService.loadTorrentFileAsResource(torrentFile.getFilepath());  //将文件加载为Spring的resource对象
//            return ResponseEntity.ok()
//                    .contentType(MediaType.parseMediaType(contentType))
//                    .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\"" + resource.getFilename() + "\"")
//                    .body(resource);
//        }catch(TorrentNotFoundException e){
//            return ResponseEntity.notFound().build();
//        }catch(Exception e){
//            return ResponseEntity.internalServerError().build();
//        }
//    }
@GetMapping("/download/{id}")
public ResponseEntity<byte[]> downloadTorrent(@PathVariable Long id, HttpServletRequest request){
    try{
        //需要加入passkey
        User user = new User(1L,"testuser");
        user.setPasskey("111111");
        String passkey = "111111";  // 先模拟一下,到时候记得改
        //获取种子文件资源
        Torrent torrentFile = torrentService.getTorrentFile(id);            //确定文件内容类型
        // 2. 原子性更新下载次数（推荐直接通过 SQL 递增）
        torrentService.incrementDownloadCount(id);  // 在 Service 层实现原子更新
        System.out.println("Requested ID: " + id);
        System.out.println("Returned Torrent: " + torrentFile);
        String filePath = torrentFile.getFilePath();
        // 解码.torrent文件
        FileInputStream fis = new FileInputStream(filePath);
        Map<String, BEValue> decoded = BDecoder.bdecode(fis).getMap();
        fis.close();

        //替换announce字段
        String announceUrl = "http://127.0.0.1:6969/announce?passkey=" + passkey;
        decoded.put("announce", new BEValue(announceUrl));
        System.out.println("Modified announce: " + decoded.get("announce"));

        //重新编码为.torrent字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BEncoder.bencode(new BEValue(decoded), baos);
        byte[] modifiedTorrent = baos.toByteArray();

        String outputPath = "D:/torrenttest/" + torrentFile.getFilename();
        try(FileOutputStream fos = new FileOutputStream(outputPath)){
            fos.write(modifiedTorrent);
        }
        System.out.println("Modified torrent bytes: " + Arrays.toString(modifiedTorrent));

        // 构建响应，下载.torrent文件
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.attachment()
                .filename(torrentFile.getFilename())
                .build());

        return new ResponseEntity<>(modifiedTorrent, headers, HttpStatus.OK);
    }catch (TorrentNotFoundException e) {
        return ResponseEntity.notFound().build();
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.internalServerError().build();
    }
}



}
